package org.yxj.videolibrary.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import org.yxj.videolibrary.R;
import org.yxj.videolibrary.i.ControlPlayListener;
import org.yxj.videolibrary.i.YXJVideoConstant;

import java.util.Formatter;
import java.util.Locale;


/**
 * 播放控制
 *
 * @author on 2022/9/9
 */
public class PlayControlView extends LinearLayout {

    /**
     * 总视频时间
     */
    private TextView tvTotalTime;

    /**
     * 播放 或 暂停
     */
    private ImageView imPlay;
    /**
     * 播放icon資源图片
     */
    private Drawable playIcon = getResources().getDrawable(R.mipmap.icon_play);
    /**
     * 暂停icon资源图片
     */
    private Drawable pauseIcon = getResources().getDrawable(R.mipmap.icon_pause);


    /**
     * 音量开关
     */
    private ImageView imVolumeOpen;


    /**
     * 当前播放时间
     */
    private TextView tvCurrentTimeView;
    /**
     * 进度
     */
    private SeekBar seekBar;
    /**
     * 记录当前播放位置
     */
    private int currentProgress;

    /**
     * 控制
     */
    private ControlPlayListener controlPlayListener;


    /**
     * 是否支持显示时间
     */
    boolean isSupportTime = false;
    public void setSupportTime(boolean supportTime) {
        isSupportTime = supportTime;
        showTimeView();
    }

    public PlayControlView(Context context) {
        this(context, null);
    }


    public PlayControlView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public PlayControlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        setBackground(getResources().getDrawable(R.drawable.video_bottom_bg));
        initPlayView();
        initTotalTime();
        initSeekBarView();
        initCurrentTimeView();
        showTimeView();
    }


    private void showTimeView() {
        if (isSupportTime) {
            tvCurrentTimeView.setVisibility(VISIBLE);
            tvTotalTime.setVisibility(VISIBLE);
        } else {
            tvCurrentTimeView.setVisibility(GONE);
            tvTotalTime.setVisibility(GONE);
        }
    }


    private void initCurrentTimeView() {
        tvCurrentTimeView = new TextView(getContext());
        tvCurrentTimeView.setTextColor(Color.WHITE);
        tvCurrentTimeView.setTextSize(12);
        tvCurrentTimeView.setPadding(20, 0, 20, 0);
        addView(tvCurrentTimeView);
    }


    private void initSeekBarView() {
        seekBar = new SeekBar(getContext());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 创建 ColorStateList
            int[][] states = new int[][]{
                    new int[]{android.R.attr.state_pressed},
                    new int[]{android.R.attr.state_selected},
                    new int[]{-android.R.attr.state_enabled},
                    new int[]{}
            };
            int[] colors = new int[]{
                    Color.WHITE,
                    Color.WHITE,
                    Color.WHITE,
                    Color.GRAY,
            };
            ColorStateList colorStateList = new ColorStateList(states, colors);
            seekBar.setProgressBackgroundTintList(colorStateList);
        }
        seekBar.setMax(100);
        seekBar.setProgress(0);
        addView(seekBar, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, 1));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentProgress = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (controlPlayListener != null) {
                    controlPlayListener.pause();
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (controlPlayListener != null) {
                    controlPlayListener.onSeekBar(currentProgress);
                    controlPlayListener.play();
                }
            }
        });
    }


    private void initTotalTime() {
        tvTotalTime = new TextView(getContext());
        tvTotalTime.setTextColor(Color.WHITE);
        tvTotalTime.setTextSize(12);
        tvTotalTime.setPadding(20, 0, 20, 0);
        addView(tvTotalTime);
    }


    /**
     * 按钮
     */
    private void initPlayView() {
        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(HORIZONTAL);
        layout.setGravity(Gravity.CENTER_VERTICAL);
        addView(layout, new LayoutParams(200, 70));
        layout.setBackgroundResource(R.drawable.storke_white_25);

        //播放按钮
        imPlay = new ImageView(getContext());
        imPlay.setPadding(10, 10, 10, 10);
        imPlay.setImageResource(R.mipmap.icon_play);
        layout.addView(imPlay, new LayoutParams(100, 70));

        //竖线
        ImageView line = new ImageView(getContext());
        line.setBackgroundColor(Color.WHITE);
        layout.addView(line, new LayoutParams(1, 50));

        //音量按钮
        imVolumeOpen = new ImageView(getContext());
        imVolumeOpen.setPadding(10, 10, 10, 10);
        imVolumeOpen.setImageResource(R.mipmap.icon_volume_close);
        layout.addView(imVolumeOpen, new LayoutParams(100, 70));
        imVolumeOpen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (controlPlayListener != null) {
                    controlPlayListener.playVolume();
                }
            }
        });

        imPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (controlPlayListener != null) {
                    if (controlPlayListener.playState() == YXJVideoConstant.STATE_PLAYING) {
                        controlPlayListener.pause();
                    } else {
                        controlPlayListener.play();
                    }
                }
            }
        });
    }


    /**
     * @param b
     */
    public void showVolumeIcon(boolean b) {
        imVolumeOpen.setImageResource(b ? R.mipmap.icon_volume_close : R.mipmap.icon_volume_open);
    }


    /**
     * 显示播放icon
     */
    public void showPlay() {
        imPlay.setImageDrawable(playIcon);
    }


    /**
     * 显示暂停icon
     */
    public void showPause() {
        imPlay.setImageDrawable(pauseIcon);
    }


    /**
     * 暂停icon资源图片
     */
    public void setPauseIcon(Drawable pauseIcon) {
        if (pauseIcon != null) {
            this.pauseIcon = pauseIcon;
        }
    }


    /**
     * 播放icon資源图片
     */
    public void setPlayIcon(Drawable playIcon) {
        if (playIcon != null) {
            this.playIcon = playIcon;
        }
    }


    /**
     * 当前进度
     *
     * @param total
     * @param progress
     */
    public void setData(int total, int progress) {
        tvTotalTime.setText(stringForTime(total));
        tvCurrentTimeView.setText(stringForTime(progress));
        seekBar.setProgress((int) (progress * 1.0 / total * 100));
    }


    /**
     * 缓冲进度
     *
     * @param secondaryProgress
     */
    public void setSecondaryProgress(int secondaryProgress) {
        seekBar.setSecondaryProgress(secondaryProgress);
    }


    /**
     * @param controlPlayListener
     */
    public void setControlPlayListener(ControlPlayListener controlPlayListener) {
        this.controlPlayListener = controlPlayListener;
    }


    /**
     * 将长度转换为时间
     *
     * @param timeMs
     * @return
     */
    private String stringForTime(int timeMs) {
        StringBuilder mFormatBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        int totalSeconds = timeMs / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }


    /**
     * @return
     */
    public GradientDrawable bg() {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setColors(new int[]{Color.parseColor("#CC000000"), Color.parseColor("#CC000000")});
        gradientDrawable.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM);
        return gradientDrawable;
    }

}
